package com.longcai.util;

import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonFormat;

import javassist.Modifier;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 实体类map转化类
 * @param <ID>
 * @author lwk
 */
public abstract class Map2class {
	/**
     * 实体对象转成Map
     * @param obj 实体对象
     * @return
     */
	public static Map<String,Object> obj2Map(Object obj){
		Map<String, Object> map = new HashMap<String, Object>();
		if(obj==null)
			return map;
		Class clazz = obj.getClass();
		Field[] declaredFields = clazz.getDeclaredFields();
		try{
			for (Field field : declaredFields) {
				field.setAccessible(true);
				map.put(field.getName(), field.get(obj));
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return map;
	}
	
	/**
     * Map转实体对象
     * @param Map 实体对象
     * @return
     */
	public static Object map2Obj(Map<String, Object> map,Class<?> clazz){
		 if (map == null) 
	            return null;
		 Object obj = null;
		try{
			obj = clazz.newInstance();
			Field[] declaredFields = obj.getClass().getDeclaredFields();
			for (Field field : declaredFields) {
				int mod = field.getModifiers();
				 if (Modifier.isStatic(mod) || Modifier.isFinal(mod))
					 continue;
				 field.setAccessible(true);
				 field.set(obj, map.get(field.getName()));
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return obj;
	}
}
